package com.xiaoluyy.demo.config;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.Properties;


@Configuration
@ComponentScan(basePackages= "com.xiaoluyy.demo")
public class PropertiesConfig {

    private static final String PROFILE_KEY = "spring.profiles.active";

    @Bean
    public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
        PropertyPlaceholderConfigurer pro= new PropertyPlaceholderConfigurer();
        String profile = getProfile();
        if (!StringUtils.isEmpty(profile)) {
            pro.setLocations(new ClassPathResource("application.properties"),
                    new ClassPathResource("application-" + profile + ".properties"));
        } else {
            pro.setLocations(new ClassPathResource("application.properties"));
        }
        return pro;
    }

    /**
     * 获取当前配置的环境profile
     * @return
     */
    public String getProfile() {
        // 默认为dev
        String profile = null;
        try {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("application.properties");
            Properties p = new Properties();
            p.load(in);
            profile = StringUtils.isEmpty(p.get(PROFILE_KEY)) ? null
                    : p.get(PROFILE_KEY) + "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return profile;
    }

}
